package com.xiaomi.baidumap.favorite.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.xiaomi.baidumap.favorite.model.LocalRepo;
import com.xiaomi.baidumap.favorite.model.RepoGroup;
import com.xiaomi.baidumap.favorite.presenter.LocalPresenter;

import java.sql.SQLException;

/**
 * Created by Administrator on 16-9-1.
 */
public class DBHelper extends OrmLiteSqliteOpenHelper{

    private static final String DB_Name = "repoFavorite";
    private static final int DB_VERSION = 2;
    private Context context;
    private static DBHelper helper;

    public static synchronized DBHelper getInstance(Context context){
        if (helper == null){
            helper = new DBHelper(context);
        }
        return helper;
    }

    public DBHelper(Context context) {
        super(context,DB_Name, null,DB_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        //创建数据库
        try {
             TableUtils.createTableIfNotExists(connectionSource, RepoGroup.class);
             TableUtils.createTableIfNotExists(connectionSource, LocalRepo.class);
            //把本地的数据添加到数据库上面
            new LocalRepoGroupDao(this).createOrUpdate(LocalPresenter.repoPresenter(context.getApplicationContext()));
            new LocalRepoDao(this).createOrUpdate(LocalPresenter.getLocalRepo(context.getApplicationContext()));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        //进行更新，先删除在添加
        try {
            TableUtils.dropTable(connectionSource,RepoGroup.class,true);
            TableUtils.dropTable(connectionSource,LocalRepo.class,true);
            onCreate(database, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
